import { _decorator, Button, CCString, Component, instantiate, Label, math, Node, Sprite, UIOpacity, UITransform, Vec2, Vec3 } from 'cc';
import { NodeName } from '../../utils/common';
import { livePlatformListApi } from '../../apis/leioie/games/live-platform';
const { ccclass, property } = _decorator;

@ccclass('StreamerCreateFormCheck')
export class StreamerCreateFormCheck extends Component {
    private check_sprite: Node = null;
    private close_button: Node = null;
    private check_option_button_node: Node = null;
    private checked_trigger_button: Node = null;

    private live_platform_json_data: [] = [];
    private submit_form: object = {};
    private need_hide_node_array: Node[] = [];

    protected onLoad(): void {
        this.node.children.forEach((button) => {
            if (button.getComponent(Button)) {
                button.on(Button.EventType.CLICK, this.onTriggerButtonClick, this);
            }
        })
        this.check_sprite = this.node.getChildByName(NodeName.StreamerCreateScene.Sprite.CheckSprite);
        this.close_button = this.check_sprite.getChildByName(NodeName.StreamerCreateScene.Button.CloseButton);
        this.check_option_button_node = this.check_sprite.getChildByName(NodeName.StreamerCreateScene.Node.CheckOptionButtonNode);

        this.close_button.on(Button.EventType.CLICK, this.onCloseButtonClick, this);
    }

    protected onDestroy(): void {
        if (this.node !== null && this.node !== undefined && this.node.name.length) {
            this.node.children.forEach((button) => {
                if (button !== null && button !== undefined && button.name.length) {
                    if (button.getComponent(Button)) {
                        button.off(Button.EventType.CLICK, this.onTriggerButtonClick, this);
                    }
                }
            })
        }
        if (this.close_button !== null && this.close_button !== undefined && this.close_button.name.length) {
            this.close_button.off(Button.EventType.CLICK, this.onCloseButtonClick, this);
        }
    }

    onTriggerButtonClick(event: InputEvent) {
        // console.log("佩妮：", event['node'].name);
        this.checked_trigger_button = event['node'];
        if (event['node'].name === 'LivePlatformButton') {
            if (!this.live_platform_json_data.length) {
                livePlatformListApi()
                    .then(res => {
                        return res.json();
                    })
                    .then(json_data => {
                        this.live_platform_json_data = json_data.results;
                        this.initCheckOptionButton(this.live_platform_json_data);
                    })
            } else {
                this.initCheckOptionButton(this.live_platform_json_data);
            }
        }
        this.check_sprite.active = true;
        
        if (!this.need_hide_node_array.length) {
            this.need_hide_node_array = this.getSiblingNode(this.checked_trigger_button);
        }
        this.hideNode(this.need_hide_node_array);
    }

    hideNode(_hide_node: Node[]) {
        /**
         * 隐藏标签
        */
        _hide_node.forEach((_node) => {
            _node.active = false;
        })
    }

    cancelHideNode(_hide_node: Node[]) {
        /**
         * 取消隐藏标签
        */
        _hide_node.forEach((_node) => {
            _node.active = true;
        })
    }

    onCloseButtonClick() {
        this.check_sprite.active = false;
        this.cancelHideNode(this.need_hide_node_array);
    }

    initCheckOptionButton(check_option_data: []) {
        let pos = this.getNodeAnglePositon(this.check_option_button_node);
        // console.log('黑夜：', pos);
        let current_line_num = 0;    // 当前行数
        let margin_weight = 5;
        

        for (let i = 0; i <= check_option_data.length - 1; i++) {
            let text = `${check_option_data[i]['id']}-${check_option_data[i]['name']}`;
            
            let button = instantiate(this.close_button);
            let label = button.getComponentInChildren(Label);
            button.getComponent(UITransform).width = 80;
            button.getComponent(UITransform).height = 50;
            let button_size = button.getComponent(UITransform).contentSize;
            
            label.string = text;
            label.fontSize = 20;
            label.lineHeight = 20;
            label.getComponent(UITransform).width = 80;
            label.getComponent(UITransform).height = 50;
            

            this.check_option_button_node.addChild(button);
            let line_button_num = Math.floor(pos.W / (button_size.x + margin_weight));    // 每行按钮的个数
            
            if (i % line_button_num === 0 && i !== 0) {
                current_line_num += 1;
            }
            // 如果放不下了，就需要换行。
            // 如果（按钮宽度 + 边距）* 个数 >= 父组件宽度，表明已经溢出了，因此需要换行。
            // 先算出有多少个按钮，如果超出最大宽度和长度就需要用滑条。
            let offset_x = (button_size.x + margin_weight * 2) * (i % line_button_num);
            let x = pos['TL'].x + offset_x;
            button.name = text;
            
            button.setPosition(new Vec3(x, pos['TL'].y - (button_size.y + margin_weight * 2) * current_line_num, 0));
            button.on(Button.EventType.CLICK, (event: TouchEvent) => {
                this.check_sprite.active = false;
                this.checked_trigger_button.getChildByName('Label').getComponent(Label).string = event['node'].name;
                // console.log('点击按钮：', this.checked_trigger_button.name);
                this.submit_form[this.checked_trigger_button.name.replace('Button', '').toLowerCase()] = parseInt(event['node'].name.split('-')[0], 10);
                this.cancelHideNode(this.need_hide_node_array);
            }, this);
        }
    }

    getNodeAnglePositon(_node: Node) {
        /**
         * 获取指定节点四个角的位置，包括x,y,z(可能没有)
        */
        // 获取节点的位置和尺寸  
        let position = _node.position; // 节点的位置  
        let width = _node.getComponent(UITransform).width; // 节点的宽度  
        let height = _node.getComponent(UITransform).height; // 节点的高度

        // 计算四个角的位置  
        // 注意：Cocos Creator 中的位置默认是以节点的锚点为基准的，所以我们需要根据锚点来调整计算  
        let anchorX = _node.getComponent(UITransform).anchorX; // 锚点的 X 值  
        let anchorY = _node.getComponent(UITransform).anchorY; // 锚点的 Y 值 

        // 左下角  
        let bottomLeft = new Vec3(position.x - anchorX * width, position.y - anchorY * height);  
        // 左上角  
        let topLeft = new Vec3(position.x - anchorX * width, position.y + (1 - anchorY) * height);  
        // 右上角  
        let topRight = new Vec3(position.x + (1 - anchorX) * width, position.y + (1 - anchorY) * height);  
        // 右下角  
        let bottomRight = new Vec3(position.x + (1 - anchorX) * width, position.y - anchorY * height);  
        // 返回包括左上、右上、右下、左下，长、宽
        return {
            'TL': topLeft, 
            'TR': topRight, 
            'BR': bottomRight, 
            'BL': bottomLeft, 
            'W': width, 
            'H': height
        }
    }

    getSiblingNode(_node: Node, parent_level: number = 1) {
        /**
         * 获取节点指定层级的父类的兄弟节点，
         * 例如parent_level=1，表示当前节点的父节点同层级的其他节点
         * 现在只能找一个层级的父类，否则要出错
        */
        
        let _node_array: Node[] = [];
        let parent_node: Node = _node;
        while (parent_level +1 > 0) {
            parent_node = parent_node.parent;
            parent_level -= 1;
        }
        parent_node.children.forEach((_child) => {
            if (_child.children.indexOf(_node) === -1) {
                _node_array.push(_child);
            }
        })
        return _node_array;
    }
}
